package com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lqjava.temp.app.confs.props.PayProps;
import com.lqjava.temp.app.domain.order.Order;
import com.lqjava.temp.app.entity.response.ComPayResponse;
import com.lqjava.temp.app.enums.UserTypeEnums;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.xiaoleilu.hutool.crypto.digest.Digester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Component
public class PaySDK {

	
	@Autowired
	PayProps payProps;
	
	public ComPayResponse getPayInfo(Order order,UserTypeEnums userType){
		ComPayResponse comPayResponse = null;
		
		String api = "https://www.xzkdkj.com/pay-ser/app/createOrder";
	    List<String> freeList = Arrays.asList(new String[]{
        		"omelL5P_OcU6Ic3RGIKV6DnpSKTw",
        		"2088202456671555",
        		"2088022125919063",
        		"2088912006757568",
        		"omelL5LqSPRKZmFQkuEx1QhNXGVY",
        		"omelL5BtFBSysWE32WvBuG1m4Wsg",
        		"2088012458532972",
        		"omelL5CoSbtjVpR__PeCQ2K1cGA8",
        });
	    
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Map<String, String> body = new HashMap<>();
        
        body.put("appid", payProps.getAppid());
        body.put("appKey", payProps.getMd5Key());
        body.put("amount", freeList.contains(order.getOpenid()) ? "1" : order.getAmount().toString());
        body.put("notifyUrl", payProps.getNotifyUri());
        
//        body.put("appid", "38ea336aa455410caa0bc0c4363048bd");
//        body.put("appKey", "800129B20B2C7F70CF53330F0E549A8A");
//        body.put("amount", "1");
//        body.put("notifyUrl", "123");
        
        body.put("orderid",  order.getNumber());
        body.put("openid", order.getOpenid());
        body.put("payType", UserTypeEnums.WECHART == userType ? "wechat" : "ali");
        body.put("describe", "星峙共享充电支付订单");
        body.put("noncestr", String.valueOf(System.currentTimeMillis()));
        body.put("sign", new PaySDK().getSign(body));
        
        String jsonContent = JSON.toJSONString(body);
        HttpEntity<String> entity = new HttpEntity<>(jsonContent, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(api, HttpMethod.POST, entity, String.class);
        
        String content = response.getBody();
        JSONObject parseObject = JSON.parseObject(content);
        if(parseObject.getBooleanValue("success")) {
        	comPayResponse = parseObject.getObject("obj", ComPayResponse.class);
        	comPayResponse.setSuccess(true);
        }else{
        	comPayResponse = new ComPayResponse();
        	comPayResponse.setSuccess(false);
        	JSONObject obj = parseObject.getJSONObject("obj");
        	Integer code = obj.getInteger("code");
        	String msg = obj.getString("msg");
        	comPayResponse.setCode(code);
        	comPayResponse.setMsg(msg);
        }
        
        return comPayResponse;
	}
	
	private String getSign(Map<String, String> map){
		String sign = "";
		try {
			TreeMap<String, String> treeMap = new TreeMap<>();
			
			map.entrySet().forEach(e -> {
				String val = e.getValue();
				treeMap.put(e.getKey(), val);
			});
			
			StringBuffer sb = new StringBuffer();
			
			treeMap.entrySet().forEach(e -> {
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			});
			sb.deleteCharAt(sb.length()-1);
			Digester md5 = SecureUtil.md5();
			sign = md5.digestHex(sb.toString().getBytes("utf-8")).toUpperCase();
			
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		return sign;
	}
	
	
	
}
